import { request } from 'node:https';
import Router from 'koa-router';
import response from '../../response.js';
import querystring from 'node:querystring';
const router = new Router();
const appid = 'wx99b1951726d8b31a';
const grant_type = 'client_credential';
const secret = 'cad8996931adff872067993eb614321e';
const access_token =
  '64_3EmIf2eiliLOqfTRr1eBbetM1aYjO0yq8chFXMu-nNYHdVcIS-il-7VK0a3OYlrXE1l6eZEJ8rXVVr-Ty4gIXkMKiR7S3iUbaut9N2YPoPhXrbU7XmjvZJUqvoYSTUaABAKLM';
const requestPromises = (options, postData) => {
  return new Promise((resolve, reject) => {
    const req = request(options, (res) => {
      res.on('data', (data) => {
        resolve(data.toString());
      });
    });
    req.on('error', (e) => {
      reject(e);
    });
    if (postData) {
      req.write(postData);
    }
    req.end();
  });
};
router.post('/getPhoneNumber', async (ctx) => {
  console.log(ctx.data);
  const { code } = ctx.data;
  if (!code) {
    ctx.body = response.fail({ msg: 'Invalid code' });
    return;
  }
  const options1 = {
    hostname: 'api.weixin.qq.com',
    path: `/sns/jscode2session?js_code=${code}&grant_type=authorization_code&appid=${appid}&secret=${secret}`,
    method: 'GET',
    port: 443,
  };
  // const postData = JSON.stringify({
  //   code,
  // });
  // const options2 = {
  //   hostname: 'api.weixin.qq.com',
  //   path: `/wxa/getpluginopenpid?access_token=${access_token}`,
  //   method: 'POST',
  //   headers: {
  //     'Content-Type': 'application/json',
  //     'Content-Length': Buffer.byteLength(postData),
  //   },
  //   port: 443,
  // };
  // const options2 = {
  //   hostname: 'localhost',
  //   path: `/api/article`,
  //   method: 'POST',
  //   headers: {
  //     'Content-Type': 'application/json',
  //     'Content-Length': Buffer.byteLength(postData),
  //   },
  //   port: 3000,
  // };
  try {
    // const getReq = await requestPromises(options1);
    // console.log('getReq', getReq);
    const postReq = await requestPromises(options1);
    console.log('postReq', postReq);
    ctx.body = response.success({ data: postReq });
  } catch (err) {
    console.error(err);
    ctx.body = response.fail();
  }
});
export default router;
